<template>
  <div class="app-container">
    <h2 style="text-align: center;">课程发布流程</h2>
    <el-steps :active="1" finish-status="success">
      <el-step title="步骤 1" description="填写课程基本信息" icon="el-icon-edit"></el-step>
      <el-step title="步骤 2" description="创建课程基本大纲" icon="el-icon-tickets"></el-step>
      <el-step title="步骤 3" description="发布课程" icon="el-icon-upload"></el-step>
    </el-steps>
    <div>
      <el-form v-loading="coversubmitloading" :model="courseinfo" :rules="rules" ref="courseinfo" label-width="100px" class="demo-ruleForm">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="courseinfo.title"></el-input>
        </el-form-item>
        <el-form-item label="总课时" prop="lessonNum">
         <el-input style="width:12.5rem;"
           type="number"
           min="0"
           placeholder="请输入课程总课时"
           v-model="courseinfo.lessonNum"
           clearable>
         </el-input>
          <!-- <el-select v-model="ruleForm.region" placeholder="请选择活动区域">
            <el-option label="区域一" value="shanghai"></el-option>
            <el-option label="区域二" value="beijing"></el-option>
          </el-select> -->
        </el-form-item>
        <el-form-item label="课程时间" required>
          <el-col :span="3">
            <el-form-item prop="courseStarttime" style="width: 11.875rem">
              <el-date-picker type="date" placeholder="选择开始日期" v-model="courseinfo.courseStarttime"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              style="width:100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
         <el-col class="line" :span="1"></el-col>
          <el-col :span="3">
            <el-form-item prop="courseEndtime" style="width: 11.875rem;margin-left: 5rem">
              <el-date-picker type="date" placeholder="选择结束日期" v-model="courseinfo.courseEndtime"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              style="width:100%;"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="课程封面" prop="cover" required="true">

          <el-col :span="6">
            <img width="150px"
              class="el-upload-list__item-thumbnail"
              :src="this.courseinfo.cover" alt=""
            >
            <el-upload
              ref="mycover"
              v-show="uploadcover"
              :limit="1"
              :file-list="filelist"
              action="http://localhost:9001/eduoss/fileoss"
              list-type="picture-card"
              :before-upload="beforeupload"
              :on-success="submitcover"
              :auto-upload="false">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img
                    class="el-upload-list__item-thumbnail"
                    :src="file.url" alt=""
                  >
                  <span class="el-upload-list__item-actions">
                   <!-- <span
                      class="el-upload-list__item-preview"
                      @click="handlePictureCardPreview(file)"
                    >
                      <i class="el-icon-zoom-in"></i>
                    </span> -->
                   <!-- <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleDownload(file)"
                    >
                      <i class="el-icon-download"></i>
                    </span> -->
                    <span
                      v-if="!disabled"
                      class="el-upload-list__item-delete"
                      @click="handleRemove(file)"
                    >
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
            </el-upload>

          </el-col>
          <el-col :span="6">

          </el-col>
        </el-form-item>
        <el-form-item label="课程价格" prop="price">
          <el-input style="width:12.5rem;"
            type="number"
            min="0"
            placeholder="请输入课程价格"
            v-model="courseinfo.price"
            clearable>
          </el-input>
        </el-form-item>
        <el-form-item label="教师">
          <el-col :span="4">
             <el-select  v-model="courseinfo.teacherId" placeholder="请选择讲师" style="width:180px">
                <el-option
                  v-for="teacher in teachers"
                  :key="teacher.id"
                  :label="teacher.name"
                  :value="teacher.id">
                </el-option>
              </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="课程分类" required="true">
          <el-col :span="4">
             <el-select v-model="courseinfo.subjectParentId" placeholder="请选择课程分类" style="width:180px" @change="gettwoclallofsubject">
                <el-option
                  v-for="subject1 in subjectone"
                  :key="subject1.id"
                  :label="subject1.title"
                  :value="subject1.id">
                </el-option>
              </el-select>
          </el-col>
          <el-col :span="4" style="margin-left: 2.5rem">
             <el-select v-model="courseinfo.subjectId" placeholder="请选择科目类别" style="width:180px">
                <el-option
                  v-for="item in subjecttwo"
                  :key="item.id"
                  :label="item.title"
                  :value="item.id">
                </el-option>
              </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="价格标签" required="">
          <el-radio-group v-model="courseinfo.free">
            <el-radio label="免费" value="1"></el-radio>
            <el-radio label="付费" value="0"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="相关资料">
          <el-upload
            class="upload-demo"
            ref="upload"
            action="http://localhost:9001/eduoss/fileoss"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :file-list="fileList"
            :on-success="successtosubmitcoursefile"
            :auto-upload="false">
            <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
            <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器</el-button>
            <el-badge v-if="coursefilelistflag==true" style="margin-left: 3rem;" :value="coursefilelist.length" class="item" type="warning">
              <el-button @click="dialogVisiblecoursefile = true" size="small">资料详情</el-button>
            </el-badge>
            <div slot="tip" class="el-upload__tip">不能上传大型文件！</div>
          </el-upload>
        </el-form-item>
        <!-- 课程资料详情 -->
        <el-dialog
          title="课程资料详情"
          :visible.sync="dialogVisiblecoursefile"
          width="90%"
          :before-close="handleClose">
          <div v-for="filecourse in coursefilelist">
            <div style="width: 92%;height: 2rem;float: left;"><a>{{filecourse.fileaddr}}</a><el-button @click="downloadcoursefile(filecourse.fileaddr)" type="text">下载</el-button></div>
            <div style="width: 2%;height: 2rem;float: left;margin-right: 0.2rem;">
              <el-button @click="deletecoursefilebyid(filecourse.id)" style="margin-right: 0.2rem;" size="mini" type="danger">删除</el-button>
            </div>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisiblecoursefile = false">取 消</el-button>
            <el-button type="primary" @click="dialogVisiblecoursefile = false">确 定</el-button>
          </span>
        </el-dialog>
        <!-- <el-form-item label="即时配送" prop="delivery">
          <el-switch v-model="ruleForm.delivery"></el-switch>
        </el-form-item> -->
       <!-- <el-form-item label="活动性质" prop="type">
          <el-checkbox-group v-model="ruleForm.type">
            <el-checkbox label="美食/餐厅线上活动" name="type"></el-checkbox>
            <el-checkbox label="地推活动" name="type"></el-checkbox>
            <el-checkbox label="线下主题活动" name="type"></el-checkbox>
            <el-checkbox label="单纯品牌曝光" name="type"></el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="特殊资源" prop="resource">
          <el-radio-group v-model="ruleForm.resource">
            <el-radio label="线上品牌商赞助"></el-radio>
            <el-radio label="线下场地免费"></el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item label="课程简介" prop="desc">
          <quill-editor v-model="courseinfo.description"></quill-editor>
          <!-- <el-input :rows="10" type="textarea" v-model="courseinfo.description" ></el-input> -->
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button :disabled="courseinfo.title.length>0? false:true" type="primary" @click="next">下一步</el-button>
          <el-button @click="resetForm('courseinfo')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

  </div>

</template>

<script>
  import course from '@/api/edu/course'
  import subject from '@/api/edu/subject'
  export default {
    data() {
      return {
        coursefilelist: [],
        coursefilelistflag: false,
        // 课程相关资料
        dialogVisiblecoursefile: false,
        fileList:[],
        coursefileupdataVo: {
          courseid: null,
          url: ''
        },

        active: 0,
        courseinfo: {
          title: '',
          subjectId: '',
          teacherId: '',
          subjectParentId: '',//一级分类 id
          lessonNum: '',//课时数
          description: '',
          cover: '',//封面
          price: '',//课程的价格
          courseStarttime: '',//课程开始时间
          courseEndtime: '',//课程结束时间
          free: ''//是否免费
        },
        teachers: [],
        subjectone: [],
        subjecttwo: [],
        courseid: '',
        ruleForm: {
          name: '',
          region: '',
          date1: '',
          date2: '',
          delivery: false,
          type: [],
          resource: '',
          desc: ''
        },
        rules: {
          title: [{
              required: true,
              message: '请输入课程名称',
              trigger: 'blur'
            },
            {
              min: 1,
              max: 50,
              message: '长度在 3 到 5 个字符',
              trigger: 'blur'
            }
          ],
          region: [{
            required: true,
            message: '请选择活动区域',
            trigger: 'change'
          }],
          type: [{
            type: 'array',
            required: true,
            message: '请至少选择一个活动性质',
            trigger: 'change'
          }],
          resource: [{
            required: true,
            message: '请选择活动资源',
            trigger: 'change'
          }],
          desc: [{
            required: false,
            message: '请填写课程简介',
            trigger: 'blur'
          }],
          courseStarttime: [{
            required: true,
            message: '请输入课程开始时间',
            trigger: 'blur'
          }],
          courseEndtime: [{
            required: true,
            message: '请输入课程结束时间',
            trigger: 'blur'
          }],
          lessonNum: [{
            type: Number,
            required: true,
            message: '请输入课程的总课时',
            trigger: 'change'
          }],
          price: [{
            type: Number,
            required: true,
            message: '请输入课程的价格',
            trigger: 'blur'
          }]
        },
        enterinfo: true,
        //封面上传的相关参数
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        uploadcover: true,
        coversubmitloading: false,
        filelist: [],
      }
    },
    created(){
      //下一页回显到本页   从路由中获取课程id参数
      if(this.$route.params && this.$route.params.id){
        this.courseid=this.$route.params.id
        console.log('测试id:',this.courseid)
        this.coursefilelistflag=true
        this.getcourseinfoById()
        course.getcoursefilelist(this.courseid).then(responsefile => {
          this.coursefilelist=responsefile.data.coursefiles
          console.log('测试返回的列表：',this.coursefilelist)
        })
      }else{
        this.getallteacherslist()
        this.getoneclassofsubject()
      }

    },
    mounted(){
      if(this.dialogImageUrl.length>1){
        this.uploadcover=false
      }else{
        this.uploadcover=true
      }
    },
    methods: {
      //下载
      downloadcoursefile(url){
        window.location.href=url
      },
      handleClose(done) {
              this.$confirm('确认关闭？')
                .then(_ => {
                  done();
                })
                .catch(_ => {});
            },
      // 回调课程相关资料的地址
      successtosubmitcoursefile(res){
        console.log('回调课程相关资料的地址',res.data.url)
        // 将url 地址保存到数据库中 post ->方法内获取课程资料列表
        this.coursefileupdataVo.courseid=this.courseid
        this.coursefileupdataVo.url=res.data.url
        if(res.data.url){
          // 保存到数据库
          course.insertcousefile(this.coursefileupdataVo).then(response => {
            console.log('测试上传文件数据:',this.coursefileupdataVo)
            this.coursefileupdataVo.courseid=this.courseid
            this.coursefileupdataVo.url=''

            // 获取文件列表
            course.getcoursefilelist(this.courseid).then(responsefile => {
              this.coursefilelist=responsefile.data.coursefiles
              console.log('测试返回的列表：',this.coursefilelist)
            })
          })
        }


      },
      // 获取课程相关资料列表 根据课程id
      getcoursefilex(){

      },
      //删除课程的文件
      deletecoursefilebyid(id){
        course.coursefiledelete(id).then(res => {
          course.getcoursefilelist(this.courseid).then(responsefile => {
            this.coursefilelist=responsefile.data.coursefiles
            console.log('测试返回的列表：',this.coursefilelist)
          })
        })
      },
      //
      // 课程相关资料上传
      submitUpload() {
              this.$refs.upload.submit();
            },








      next() {
        if(this.courseinfo.id){//修改操作
          //如果封面有更新 先上传封面
          console.log('测试修改时封面是否修改：',this.$refs['mycover'].uploadFiles.length)
          if(this.$refs['mycover'].uploadFiles.length>0){
            this.coversubmitloading=true
            this.submitcoverto()
            console.log('测试回调的封面地址：',this.courseinfo.cover)
          }else{
            course.updatecourseinfobyid(this.courseinfo)
            //跳转到第二步
            this.$router.push({
              path: '/course/chapter/'+this.courseid
            })
          }


        }else{//没有id的时候做添加操作
          //加载等待
          if(this.courseinfo.title.length!=0){

            //先上传封面 返回url
            if(this.$refs['mycover'].uploadFiles.length>0){
              this.coversubmitloading=true
              this.submitcoverto()
              console.log('测试回调的封面地址：',this.courseinfo.cover)
            }
          }
          else{
            this.$message({
              type: 'erro',
              message: '请填写课程名称'
            })
          }
        }



          //保存
        // if (this.active++ > 2) this.active = 0;
      },
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      },
      //获取讲师列表
      getallteacherslist(){
        course.getallteachers().then(response =>{
          this.teachers=response.data.items
          console.log('测试讲师：',this.teachers)
          // console.log('test_teacherlist:',this.teachers)
        })
      },
      //获取课程一级分类列表
      getoneclassofsubject(){
        subject.getsubjectbytree().then(response =>{
          this.subjectone=response.data.data
          console.log('test_subjectoneclass:',this.subjectone)
        })
      },
      //货物课程二级分类列表
      gettwoclallofsubject(pid){
        this.courseinfo.subjectId=''
        for(var i=0;i<this.subjectone.length;i++){
          if(this.subjectone[i].id===pid){
            this.subjecttwo=this.subjectone[i].children
          }
        }
      },
      //封面上传的相关方法
      handleRemove(file) {
              this.$refs['mycover'].clearFiles()//x
            },
      handlePictureCardPreview(file) {
              this.dialogImageUrl = file.url;
              this.dialogVisible = true;

          },
      handleDownload(file) {
              console.log(file);
       },
      removecover(file){
        file.destroy()
      },
      coveronchange(){
        this.uploadcover=false
      },
      submitcoverto(){
        this.$refs['mycover'].submit()
      },
      //上传课程的封面 然后回调返回 封面的url
      submitcover(res){
        this.courseinfo.cover=res.data.url
        this.$message({
          type: 'success',
          message: '封面已上传'
        })
        //判断是否是修改操作
        if(this.courseinfo.id){
          course.updatecourseinfobyid(this.courseinfo)
          //给用户的提示信息
          this.$message({
            type: 'success',
            message: '保存信息成功'
          });
          this.coversubmitloading=false
          //跳转到第二步
          this.$router.push({
            path: '/course/chapter/'+this.courseid
          })
        }else{
          //上传封面  回调url 再保存课程信息
          course.addcouseinfo(this.courseinfo).then(response => {
            //给用户的提示信息
            this.$message({
              type: 'success',
              message: '保存信息成功'
            });
            this.coversubmitloading=false
            //跳转到第二步
            this.$router.push({
              path: '/course/chapter/'+response.data.courseid
            })
          })
        }

      },
      //根据courseid 查询信息
      getcourseinfoById(){
        course.getcourseinfobyidx(this.courseid).then(response => {
          this.courseinfo=response.data.courseInfoVo
           this.getallteacherslist()
          //回显查询所有的分类，包含一级分类与二级分类

          subject.getsubjectbytree().then(response =>{
            this.subjectone=response.data.data//回显的时候先获取课程的所有一级分类
            for(var i=0;i<this.subjectone.length;i++){
              var oneclasssubject=this.subjectone[i]
              if(this.courseinfo.subjectParentId==oneclasssubject.id){
                this.subjecttwo=oneclasssubject.children
              }
            }
          })

          console.log(this.courseinfo)
        })
      },
    }

  }
</script>

<style>
</style>
